// pages2/pages/mall/activity/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import { clearShopCartStorage } from '../../../../utils/hooks';
const $api = require('../../../../request/api').API;
const app = getApp();
const colorContainer = ['#07C160', '#1989FA', '#8148AD', '#FF9FB7', '#FF976A'];
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    page: {
      pageNo: 1,
      totalPage: 1,
      pageSize: 10
    },
    beeperId: '',
    btnId: '',
    secondClassifyIds: '',
    linkUrl: '',
    showSignUp: false,
    btnList: [],
    buyType: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { globalData } = app;
    this.setData({
      beeperId: globalData['btnList.beeperId'],
      secondClassifyIds: globalData['btnList.btnServerClassifyIds'],
      linkUrl: globalData['btnList.linkUrl'],
      btnId: globalData['btnList.btnId'],
      btnType: globalData['btnList.btnType'],
      queryType: globalData['btnList.queryType'],
      addressType: globalData['btnList.addressType']
    });
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  // 获取数据
  async getData() {
    const { page, List, secondClassifyIds, beeperId } = this.data;
    const { pageNo, pageSize } = page;
    const params = {
      pageNo,
      pageSize,
      secondClassifyIds,
      beeperId
    };
    const res = await $api.activityList(params);
    const data = res.data.data;
    const { list } = data || [];
    // 遍历数据获取选中按钮的名字
    list.forEach(item => {
      if (item.activityType == 2) {
        item.list.forEach(item2 => item2.selected && (item.selectedName = item2.btnName));
      }
    });
    page.totalPage = data.totalPage;
    this.setData({
      page,
      list: pageNo == 1 ? list : List.conact(list)
    });
  },
  // 点击主按钮或者修改按钮
  async clickOperation(e) {
    // 临时保存的数据
    this.tempData = e.currentTarget.dataset.item;
    const { activityId, list, activityType } = this.tempData;
    let res = list;
    if (activityType == 1) {
      // 产品类型
      res = await $api.listChildBtn({ activityId });
      res = res.data.data;
      res.forEach((item, index) => (item.color = colorContainer[index]));
      if (res.length == 1) {
        // 如果没有按钮后端会抛出异常所以不用判断没有的情况
        this.clickBtn({ currentTarget: { dataset: { item: res[0] } } });
        return;
      }
    } else {
      res.forEach((item, index) => (item.color = colorContainer[index]));
    }
    this.setData({
      btnList: res,
      showSignUp: true
    });
  },
  // 去活动详情页面
  toActivityDetail(e) {
    const { beeperId, secondClassifyIds, btnId, btnType, queryType, linkUrl } = this.data;
    let params = {
      ...e.currentTarget.dataset.item,
      beeperId,
      btnId,
      btnType,
      classifyIds: secondClassifyIds,
      queryType,
      linkUrl
    };
    params = encodeURIComponent(JSON.stringify(params));
    wx.navigateTo({
      url: '/subcontract/home/pages/activityDetail/index?params=' + params
    });
  },
  // 点击弹框里面的选择按钮
  async clickBtn(e) {
    // 注意区分activityid与activityId
    const {
      item: { activityServerId, btnName },
      activityid
    } = e.currentTarget.dataset;
    const { beeperId, addressType, secondClassifyIds, btnId, btnType, queryType, list, linkUrl } = this.data;
    const { buyWay, activityType, activityId } = this.tempData || {};
    let res = null;
    if (activityType == 1) {
      // 产品类型
      Toast.loading({
        message: '正在加载中',
        forbidClick: true,
        mask: true
      });
      res = await $api.getGoodsByBtn({ activityServerId, beeperId });
      const { goods, addressInfo, attr } = res.data.data;
      if (buyWay == 13 || buyWay == 14) clearShopCartStorage();
      const buyType = {
        eventId: buyWay,
        beeperId,
        id: btnId,
        btnType,
        classifyIds: secondClassifyIds,
        queryType,
        btnName,
        linkUrl,
        orderSource: 5,
        sourceId: activityId,
        attr
      };
      // 这里的orderSource为5表示活动下单
      buyType.goods = { ...goods, nums: 1 };
      console.log(buyType.goods, goods);
      buyType.addressInfo = { ...addressInfo, addressType };
      this.setData({
        buyType
      });
      Toast.clear();
    } else {
      /**
       * 只要activityType不为1就是通知类型，
       * 因为如果是三个按钮在列表中都显示出来了是获取不到tempData的，
       * 这个时候tempData会是空
       */
      await Dialog.confirm({
        title: '提示',
        message: '确定修改为' + btnName + '？',
        zIndex: '10'
      });
      res = await $api.setActivityRecord({ activityId: activityid || activityId, btnName });
      res = res.data.data;
      Toast.success('操作成功');
      list.find(item => item.activityId == (activityid || activityId) && (item.selectedName = btnName));
      this.setData({
        list
      });
    }
    this.setData({
      showSignUp: false
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
